/**
 * tinymce plugin - upload image
 * Created by landy on 2018/02/08.
 */
tinymce.PluginManager.add('uploadimage', function (editor) {

    function selectLocalImages() {
        var dom = editor.dom;
        //var input_f = $('<input type="file" name="thumbnail" accept="image/jpg,image/jpeg,image/png,image/gif" multiple="multiple">');
        var input_f = $('<input type="file" name="file" accept="image/jpg,image/jpeg,image/png,image/gif">');

        input_f.on('change', function () {
                var form = $("<form/>",
                    {
                        action: editor.settings.upload_image_url, //设置上传图片的路由，配置在初始化时
                        style: 'display:none',
                        method: 'post',
                        enctype: 'multipart/form-data'
                    }
                );
                form.append(input_f);
                //ajax提交表单
            var file = input_f[0].files[0];
            if (!file) {
                return false;
            }
            var formData = new FormData();
            formData.append('path', 'editor');
            formData.append('file', file);
            //ajax提交表单
            $.ajax({
                url: editor.settings.upload_image_url,
                data: formData,
                type: 'post',
                cache: false,       //上传文件无需缓存
                processData: false, //用于对data参数进行序列化处理 这里必须false
                contentType: false, //必须
                success: function (result) {
                    if (result.code === 200) {
                        editor.focus();
                        editor.selection.setContent(dom.createHTML('img', {src: ctx + 'common/download/' + result.param}));
                    } else {
                        editor.notificationManager.open({
                            text: result.msg,
                            type: 'error'
                        });
                    }
                }
            });
            }
        );

        input_f.click();
    }

    editor.addCommand("mceUploadImageEditor", selectLocalImages);

    editor.addButton('uploadimage', {
        icon: 'image',
        tooltip: '上传图片',
        onclick: selectLocalImages
    });

    editor.addMenuItem('uploadimage', {
        icon: 'image',
        text: '上传图片',
        context: 'tools',
        onclick: selectLocalImages
    });
});